package com.liudadan.interceptors;


import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * projectName: com.atguigu.interceptors
 * description:
 *  1. 创建一个类实现拦截器接口HandlerInterceptor
 *  2. 选择重写三个方法 preHandle postHandle afterCompletion
 *  3. mvc对应ioc配置文件中，声明拦截地址
 *     <mvc:interceptors>
 *         <bean class="com.atguigu.interceptors.MyInterceptor" />
 *     </mvc:interceptors>
 */

public class MyInterceptor implements HandlerInterceptor {

    /**
     * pre -> 前
     * preHandle -> 调用handler之前
     * boolean -> 是否放行 true 放行 | false 拦截
     * 登录保护 || 编码格式 ...
     * @param request 请求对象
     * @param response 响应对象
     * @param handler 调用目标handler
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("MyInterceptor.preHandle");
        System.out.println("request = " + request + ", response = " + response + ", handler = " + handler);
        //response (json | 转发 | 重定向)
        return true;
    }

    /**
     * post -> 后
     * postHandle -》 handler执行以后调用
     * 我骂人，变成 **  以及扣信誉分！！
     * postHandle已经不能再拦截了！！（亡羊补牢） + 如果handler报错，此方法也不执行！！
     *
     * @param request 请求对象
     * @param response 响应对象
     * @param handler 目标方法
     * @param modelAndView 本次返回的视图和共享域数据 || @ResponseBody 为null
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("MyInterceptor.postHandle");
        System.out.println("request = " + request + ", response = " + response + ", handler = " + handler + ", modelAndView = " + modelAndView);
    }

    /**
     * after -> ceo返回前端数据之前调用
     * 对比： postHandle的区别就是，他更靠后，不管报不报错，一定执行！！
     * @param request 请求
     * @param response 响应
     * @param handler 目标处理器方法
     * @param ex 报错了，获取错误信息
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("MyInterceptor.afterCompletion");
        System.out.println("request = " + request + ", response = " + response + ", handler = " + handler + ", ex = " + ex);
    }
}
